package com.youdianda.interceptor;


import com.youdianda.context.BaseContext;
import com.youdianda.properties.JwtProperties;
import com.youdianda.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    private String token;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }



        //1、从请求头中获得token/authentication
        String header1 = request.getHeader("x-token");
        String header2 = request.getHeader("token");


        if(header1 == null && header2 == null){
            response.setStatus(401);
        }else if(header1 == null){
            token = header2;
            log.info("这是header2：用户端的token=============");
            log.info("拿到的token：{}" + token);
        }else{
            token = header1;
            log.info("这是header1：管理端的token-------------");
            log.info("拿到的token：{}" + token);
        }



        //2、判断token是否有效
        Claims claimsBody = JwtUtil.getClaimsBody(token);//获得token的有效载荷，
        int i = JwtUtil.verifyToken(claimsBody);    //传入有效载荷，进行校验，得到返回值参数，确实是否有效

        //3、根据i的值，看拦截器是否放行：
        if(i == -1 || i == 0){
            //获得当前登录用户的ID，并封存到线程里。
            Integer id = (Integer) claimsBody.get("id");
            BaseContext.setCurrentId(id.longValue());

            return true;
        }else {
            response.setStatus(401);
            return false;
        }
    }
}
